import { useStore } from '@/hooks';
import { Button, Dialog, Form } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid, ENUMS, TitleGrid } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';

const FromItem = Form.Item;

const DataForm = ({ id, onCancel, modal, onSubmit, ...formProps }) => {
  const { taskStore: store } = useStore();
  const {
    show,
    record,
    toClose,
  } = modal;
  const [driver] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(show === 'view');

  useEffect(() => { if (toClose?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      if (id) {
        const res = await store.get(id);
        editCtx.origin = _.cloneDeep(res);
        _.assign(driver, res);
        findDriver(res?.driverInfos);
      }
    })();
  }, []);

  function findDriver(arr) {
    if (!arr || arr.length == 0) {
      return;
    }
    const data = _.cloneDeep(arr);
    const filterData = data.filter((p) => p.status !== '0');
    if (filterData.length > 0) {
      const { driverId, driverName, driverPhone, status, takeOrderTime } = filterData[0];
      _.assign(driver, {
        'driverInfos.driverId': driverId,
        'driverInfos.driverName': driverName,
        'driverInfos.driverPhone': driverPhone,
        'driverInfos.status': ENUMS.driverStatus[status],
        'driverInfos.takeOrderTime': takeOrderTime,
      });
    }
  }

  const overrideModel = {
  };

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(driver, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: ActivityForm.jsx:213 _ errors:', errors);
      return;
    }
    onSubmit?.(driver);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      {...formProps}
      value={driver}
      onChange={handleChange}
      inline
      useLabelForErrorMessage
    >
      <TitleGrid title={t`基本信息`} />
      <FieldsGrid
        formData={driver}
        mode={'view'}
        overrideModel={overrideModel}
        fields={[
          'taskId', 'groupName', 'price', 'predictBeginDate',
          'publisherName', 'publisherPhone',
          'issueOrderPoint', 'takeOrderPoint',
          'driverInfos.driverName', 'driverInfos.driverPhone', 'driverInfos.status', 'driverInfos.takeOrderTime',
          'crDate', 'content']}
      />
      <FieldsGrid
        formData={driver}
        mode={show}
        overrideModel={overrideModel}
        fields={['status']}
      />
      <TitleGrid title={t`备注信息`} />
      <FieldsGrid
        formData={driver}
        mode={'view'}
        overrideModel={overrideModel}
        fields={['remark']}
      />
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};

export default observer(DataForm);
